/**
 * FtpUpload.java
 * 版权所有(C) 2013
 * 创建者:cuiran 2013-12-3 上午10:24:49
 */
package com.ghyf.mplay.net.ftp;

import java.io.IOException;

import com.ghyf.mplay.application.BaseCookie;
import com.ghyf.mplay.application.CookieConstants;
import com.ghyf.mplay.application.UserInfoSingleton;
import com.ghyf.mplay.net.common.RecvBase;
import com.ghyf.mplay.net.data.ConfigFtpData;
import com.ghyf.mplay.net.ftp.FtpClientUtil.DownloadStatus;
import com.ghyf.mplay.util.LogUtil;
import com.ghyf.mplay.util.ShellUtils;
import com.ghyf.mplay.util.ShellUtils.CommandResult;
import com.ghyf.mplay.value.ConstantValue;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;

/**
 * FTP 上传下载操作类
 * @author cuiran
 * @version 1.0.0
 */
public class FtpUpload {
	private static final String TAG="FtpUpload";
	private FtpClientUtil ftpClient=null;
	private boolean isFile=false;
	private String filepath;
	private Context mContext=null;
	private DownLoadTask downLoadTask=null;
	
	
	public FtpUpload(Context context,Handler handler) {
		
		ftpClient=new FtpClientUtil(context, handler);
		mContext=context;
	}
	
	/**
	 * 上传文件--》单个文件<br>
	 * 2013-12-3 上午10:30:53
	 * @param filepath 上传文件路径
	 * @param ftpData ftp数据
	 */
	public synchronized void uploadFile(ConfigFtpData ftpData,String filepath){
		try{
			isFile=true;
			this.filepath=filepath;
			new UploadTask(ftpData).execute();
		}catch(Exception e){
			LogUtil.e(TAG, "uploadFile出现异常",e);
		}
	}
	/**
	 * 下载文件 --》单个文件<br> 采用同步
	 * 2013-12-9 上午10:39:23
	 * @param ftpData
	 * @param filepath
	 *
	 */
	public synchronized void downloadFile(ConfigFtpData ftpData){
		try{
			isFile=true;
			downLoadTask=new DownLoadTask(ftpData);
			downLoadTask.execute();
		}catch(Exception e){
			LogUtil.e(TAG, "downloadFile出现异常",e);
		}
	}
	
	
	

	class UploadTask extends AsyncTask<Object, Object, Object>{
		private ConfigFtpData ftpData=null;
		
		private UploadTask(ConfigFtpData ftpData) {
			super();
			this.ftpData = ftpData;
		}

		/* (non-Javadoc)
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		@Override
		protected Object doInBackground(Object... obj) {
			
			try {
			boolean flag=ftpClient.connect(ftpData.getIp(),
						ftpData.getPort(), 
						ftpData.getUsername(),
						ftpData.getPassword());
			LogUtil.i(TAG, "UploadTask flag="+flag);
				if(flag){
					if(isFile){
//						File file=new File(filepath);
						// /log/
//						ftpClient.upload(filepath, "/log/"+file.getName());
						
						ftpClient.uploadprocess(filepath, "/"+ConstantValue.SERVER_LOG);
					}
					
				}
				
			} catch (Exception e) {
				
				LogUtil.e(TAG, "doInBackground error", e);
			}
			
			return null;
		}

		/* (non-Javadoc)
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(Object result) {
			
			super.onPostExecute(result);
		}

		/* (non-Javadoc)
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			
			try {
				if(ftpClient!=null){
					ftpClient.disconnect();
				}
				
			} catch (IOException e) {
			
				e.printStackTrace();
			}
			
			super.onPreExecute();
		}
		
	}
	boolean isSuccess=true;
	class DownLoadTask extends AsyncTask<Object, Integer, Object>{
		private	ConfigFtpData ftpData=null;
		
		private DownLoadTask(ConfigFtpData ftpData) {
			super();
			this.ftpData = ftpData;
		}


		/* (non-Javadoc)
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		@Override
		protected  Object doInBackground(Object... obj) {
			DownloadStatus result=null;
			try {
				LogUtil.i(TAG, "FTP开始连接"+ftpData.getIp()+"--"+ftpData.getUsername()+"--"+ftpData.getUsername().length()+"--"+ftpData.getPassword());
				boolean flag=ftpClient.connect(ftpData.getIp(),
						ftpData.getPort(), 
						ftpData.getUsername(),
						ftpData.getPassword());
				if(flag){
					LogUtil.i(TAG, "FTP连接成功");
					if(isFile){
						switch(ftpData.getCmdId()){
						
							case RecvBase.CMD_FILE_SETCONFIG:
								
								if(!"0".equals(ftpData.getSoftwareFilename())&&!"".equals(ftpData.getSoftwareFilename())&&null!=ftpData.getSoftwareFilename()){
									filepath=ftpData.getSoftwareFilename();
									LogUtil.i(TAG, "FTP开始下载文件"+filepath);
									ftpClient.download(ConstantValue.SERVER_APP+"/"+filepath, ConstantValue.ROOT_SDCARD_DIR+"MPlay.apk");
								}
								
								if(!"0".equals(ftpData.getConfigFilename())&&!"".equals(ftpData.getConfigFilename())&&null!=ftpData.getConfigFilename()){
									filepath=ftpData.getConfigFilename();
									LogUtil.i(TAG, "FTP开始下载文件"+filepath);
									ftpClient.download(ConstantValue.SERVER_APP+"/"+filepath, ConstantValue.ROOT_DIR+filepath);
								}
									
								break;
							case RecvBase.CMD_FILE_SETLIST:
								filepath=ftpData.getListFilename();
								//1、先下载文件  2、下载完成进行对资源文件检测
								result=ftpClient.downloadprocess(ConstantValue.SERVER_PLAYLIST+"/"+filepath+"/",ConstantValue.ROOT_DIR+ filepath+"/");
								if(result.equals(DownloadStatus.Download_New_Failed)){
									isSuccess=false;
									LogUtil.i(TAG, "播表下载出现异常，记录并重新下载!!!");
								}
								break;
						}
						LogUtil.i(TAG, "FTP下载结束");
					}
					
				}
				
			} catch (Exception e) {
				isSuccess=false;
				LogUtil.e(TAG, "doInBackground error", e);
			}
			
			return null;
		}

	
		@Override
		protected void onPostExecute(Object result) {
		
			super.onPostExecute(result);
			try {
				UserInfoSingleton.putBooleanAndCommit(CookieConstants.IsDownload, false);
				LogUtil.i(TAG, "O(∩_∩)O下载完成后 执行相应操作  isSuccess》》》》"+isSuccess);
				if(!isSuccess){
					/**
					 * 失败对其进行记录
					 */
					UserInfoSingleton.saveObject(CookieConstants.ConfigFtpData, ftpData);
					UserInfoSingleton.putBooleanAndCommit(CookieConstants.IsDownloadFail, true);
					
				}else{
					UserInfoSingleton.putBooleanAndCommit(CookieConstants.IsDownloadFail, false);
					switch(ftpData.getCmdId()){
					
					case RecvBase.CMD_FILE_SETCONFIG:
						if(!"0".equals(ftpData.getSoftwareFilename())&&!"".equals(ftpData.getSoftwareFilename())&&null!=ftpData.getSoftwareFilename()){
							BaseCookie.getInstance().sendAppInstall();
						}else{
							if(!"0".equals(ftpData.getConfigFilename())&&!"".equals(ftpData.getConfigFilename())&&null!=ftpData.getConfigFilename()){
								BaseCookie.getInstance().sendCmd(mContext, ConstantValue.RESOFTWARE_RECEIVER);
							}
						}
						
						break;
					case RecvBase.CMD_FILE_SETLIST:
						 UserInfoSingleton.setPlayPath(ConstantValue.ROOT_DIR + filepath+"/");
						//下载完执行chmod 777 
						// 初始化事件文件的权限
						CommandResult cr = ShellUtils.execCommand("busybox chmod -Rf 777 " + ConstantValue.ROOT_DIR + filepath+"/",ShellUtils.checkRootPermission()) ;
						LogUtil.i(TAG, "chmodeth：successMsg="+cr.successMsg+"-result="+cr.result+"-errorMsg="+cr.errorMsg);
				
						Intent mIntent = new Intent(RecvBase.ACTION_CMD_CONTROL);
						mIntent.putExtra("cmd", RecvBase.CMD_FILE_SETLIST);
						//发送广播
						mContext.sendBroadcast(mIntent);
						
						break;
					}
					
				}
			} catch (Exception e) {
			
				LogUtil.e(TAG, "onPostExecute error", e);
			}
			
		}

		/* (non-Javadoc)
		 * @see android.os.AsyncTask#onProgressUpdate(Progress[])
		 */
		@Override
		protected void onProgressUpdate(Integer... values) {
		}


		/* (non-Javadoc)
		 * @see android.os.AsyncTask#onPreExecute()
		 */
		@Override
		protected void onPreExecute() {
			
			try {
				if(ftpClient!=null){
					ftpClient.disconnect();
				}
				LogUtil.i(TAG, "下载开始");
			} catch (IOException e) {
				
				LogUtil.e(TAG, "onPostExecute error", e);
			}
			
			super.onPreExecute();
		}
		
	}
	
	
}
